package wens.pig.dhm.formplugin.patrolscheme;

import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.entity.BasedataEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.BasedataProp;
import kd.bos.entity.property.MulBasedataProp;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterBindingDataEvent;
import kd.bos.form.field.events.BasedataEditListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.lang3.StringUtils;
import wens.pig.base.common.consts.dhm.PatrolPlanConstant;
import wens.pig.base.common.consts.dhm.PatrolRecordConstant;
import wens.pig.base.utils.QFilterUtils;
import wens.pig.base.utils.ToolUtils;
import wens.pig.dhm.util.EnvSamSchemeUtils;

import java.util.EventObject;

/**
 * 巡查计划页面插件
 * coyle
 */
public class PatrolPlanFormPlugin extends AbstractFormPlugin implements BasedataEditListener, RowClickEventListener, HyperLinkClickListener {


    private static final String BASEDATA_FIELD = "wens_three";
    private static final String CUSNAME = "wens_custom_name";
    private static final String NAME = "name";
    private static final String BILLCANCEL = "cancelplanbut";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        // 监听分录行
        EntryGrid entryGrid = this.getView().getControl(PatrolPlanConstant.ENTRYENTITYID_WENS_ENTRYDETAIL);
        entryGrid.addHyperClickListener(this);
        this.addItemClickListeners("tbmain");

    }






    @Override
    public void initialize() {
        super.initialize();
        this.getModel().addDataModelChangeListener(this);
        BasedataEdit wens_three = this.getControl(BASEDATA_FIELD);
        wens_three.addBasedataEditListener(this);
    }


    @Override
    public void afterBindingData(AfterBindingDataEvent evt) {
        BasedataEdit edit = (BasedataEdit) evt.getSource();
        if ("wens_three".equals(edit.getKey())) {
            //采样三级的显示属性
            Object v = evt.getDataEntity();
            Object displayProp = "";
            if (v == null) {
                return;
            }
            BasedataEntityType dt;
            if (((DynamicObject) v).getDataEntityType() instanceof BasedataEntityType) {
                dt = (BasedataEntityType) ((DynamicObject) v).getDataEntityType();
            } else {
                dt = (BasedataEntityType) ((BasedataProp) edit.getProperty()).getComplexType();
            }

            //获取数据包中的名称字段值
            String nameKey = dt.getNameProperty();
            IDataEntityProperty p2 = dt.findProperty(nameKey);
            if (p2 != null) {
                displayProp = p2.getValueFast(v);
                if (displayProp instanceof ILocaleString) {
                    displayProp = displayProp.toString();
                }
            }
            IDataEntityProperty p4 = dt.findProperty("fullname");
            if (p4 != null) {
                String fullname = p4.getValueFast(v).toString();
                String[] split = fullname.replace(".", "-").split("-");
                if (split.length > 3) {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < split.length; i++) {
                        if (i < 2) {
                            continue;
                        }
                        sb.append(split[i]);
                        if (i != split.length - 1) {
                            sb.append(".");
                        }
                    }
                    if (sb.length() > 0) {
                        displayProp = String.format("%s", sb.toString());
                    } else {
                        displayProp = String.format("%s", displayProp.toString());
                    }
                } else {
                    displayProp = String.format("%s", displayProp.toString());
                }
            }

            String editSearchProp = getEditSearchProp(edit.getProperty());
            //编辑显示属性也同步修改
            if (StringUtils.isNotBlank(editSearchProp)) {
                editSearchProp = editSearchProp
                        .replace("number", displayProp == null ? "" : displayProp.toString());
            }

            //设置显示属性
            evt.setDisplayProp(displayProp.toString());
            //设置编辑显示属性
            evt.setEditSearchProp(editSearchProp == null ? "" : editSearchProp.toString());
        }
    }



    /**
     * 获取配置的编辑显示属性
     *
     * @param property
     * @return
     */
    private String getEditSearchProp(IDataEntityProperty property) {
        BasedataProp basedataProp = null;

        if ((property instanceof BasedataProp)) {
            basedataProp = (BasedataProp) property;
        } else if (property instanceof MulBasedataProp) {
            basedataProp = (BasedataProp) ((MulBasedataProp) property).getRefBaseProp();
        }

        return basedataProp.getEditSearchProp();
    }



    @Override
    public void hyperLinkClick(HyperLinkClickEvent hyperLinkClickEvent) {
        //  获取超链接点击的属性名
        String fieldName = hyperLinkClickEvent.getFieldName();
        //  获取点击分录行的下标
        if (StringUtils.containsIgnoreCase(fieldName,PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO )){
            int rowIndex = hyperLinkClickEvent.getRowIndex();
            // 获取超链接信息  单据编号
            String billNum = ToolUtils.cnulls(this.getModel().getValue(fieldName, rowIndex));
            if(StringUtils.isNotBlank(billNum)){
                QFilter qFilter = QFilterUtils.getBillQFilter();
                qFilter.and(PatrolRecordConstant.BILLNO, QCP.equals,billNum);
                DynamicObject object = BusinessDataServiceHelper.loadSingle(PatrolRecordConstant.FORMBILLID, PatrolRecordConstant.ID, qFilter.toArray());
                EnvSamSchemeUtils.openView(this.getView(), PatrolRecordConstant.FORMBILLID,ToolUtils.cnulls(object.getPkValue()) ,OperationStatus.VIEW);
            }
        }
    }



    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String itemKey = evt.getItemKey();
        if("wens_cancelplan".equals(itemKey)){
            IDataModel model = this.getModel();
            DynamicObject planObj = model.getDataEntity(true);
            int sampledqty = planObj.getInt("wens_sampledqty");
            if(sampledqty > 0 ){
                this.getView().showTipNotification("此计划已生成<巡查记录>,请先删除对应单据,再执行作废!",5000);
                /*ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener(BILLCANCEL, this);
                this.getView().showConfirm("当前计划已完成部分采样，是否仍需作废?", MessageBoxOptions.YesNo,
                        ConfirmTypes.Default, confirmCallBacks);*/
            }else{
                ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener(BILLCANCEL, this);
                this.getView().showConfirm("是否确认作废此数据?", MessageBoxOptions.YesNo,
                        ConfirmTypes.Default, confirmCallBacks);
            }
        }
    }

    /**
     * 作废功能
     * coyle
     */
    private  void  setCancelBill(){
        try {
            OperationResult cancelplan = this.getView().invokeOperation("cancelplan");
            if(cancelplan.isSuccess()){
                this.getView().showSuccessNotification("操作成功!");
                this.getView().updateView("wens_exestate_head");
            }
        }catch (Exception e){
            this.getView().showErrorNotification("操作失败"+e.getMessage());
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent evt) {
        super.confirmCallBack(evt);
        if (StringUtils.equals(BILLCANCEL, evt.getCallBackId())
                && evt.getResult() == MessageBoxResult.Yes){
            setCancelBill();
        }
    }

}
